package com.loveprogrammer.codec;

import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.pojo.CodeMessage;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.Charset;

/**
 * @ClassName MessageEncoder
 * @Description 消息编码器
 * @Author admin
 * @Date 2024/1/31 10:40
 * @Version 1.0
 */
public class MessageEncoder extends MessageToByteEncoder<CodeMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, CodeMessage msg, ByteBuf out) throws Exception {
        if(null == msg) {
            throw new Exception("msg is null");
        }
        String body = msg.getBody();
        byte[] bodyBytes = body.getBytes(Charset.forName(ConstantValue.PROJECT_CHARSET));
        out.writeInt(msg.getCode());
        out.writeInt(msg.getStatusCode());
        out.writeInt(bodyBytes.length);
        out.writeBytes(bodyBytes);
    }
}
